<template>
    <div class='buy-container'>
        <navcon></navcon>
        <form action="" method="post" id="alipay" :model="payVo">
            <input type="hidden" v-model="payVo.traceNo" name="traceNo" id="traceNo">
            <input type="hidden" v-model="payVo.totalAmount" name="totalAmount" id="totalAmount">
            <input type="hidden" v-model="payVo.subject" name="subject" id="subject">
            <input type="hidden" v-model="payVo.alipayTraceNo" name="alipayTraceNo" id="alipayTraceNo">
            <input type="hidden" v-model="payVo.returnUrl" name="returnUrl" id="returnUrl">
            <div class="bc-container">
                <!-- 收货地址 -->
                <span class="change-tip">请选择地址</span>
                <div class="change-address">
                    <div class="cad-main">
                        <div class="address-box" v-for="address in addressList" :key="address.id"
                            :class="defaultAddress == address.id ? 'address-bgc' : ''"
                            @click="changeDefaultAddress(address)">
                            <div :class="defaultAddress"></div>
                            <div class="adb-head">{{ address.province }}{{ address.city }}（{{ address.name }}收）</div>
                            <div class="adb-all-detail">{{ address.detailAddress }} {{ address.phone }}</div>
                        </div>
                    </div>
                </div>
                <span class="manage-address"><span @click="manageAddress()">管理收货地址</span></span>
                <!-- 确认订单信息 -->
                <span class="enter-orderinfo">确认订单信息</span>
                <div class="product-info">
                    <div class="pi-head">
                        <div>商品信息</div>
                        <div>商品属性</div>
                        <div>价格</div>
                        <div>数量</div>
                        <div>小计</div>
                    </div>
                </div>

                <div v-for="product in productList" :key="product.memberId">
                    <div class="sellerinfo">
                        <div class="sellerhead">
                            <img :src="product.header" alt="">
                        </div>
                        <div class="sellername">
                            <span>商品发布者:
                                <span>{{ product.nickname }}</span>
                            </span>
                        </div>
                    </div>
                    <!-- 商品信息 -->
                    <div class="product-detail">
                        <div class="left">
                            <div class="product-img">
                                <img :src="product.spuImage" alt="">
                            </div>
                            <div class="pd-product-detail">
                                <span v-html="product.spuDetail.replaceAll('<br>', '\n')"></span>
                            </div>
                        </div>
                        <div class="all-attr">
                            <div v-for="attr in product.attrInfos" :key="attr.id">
                                <div>{{ attr.name }}: {{ attr.value }}</div>
                            </div>
                        </div>
                        <div class="price">
                            <span>￥{{ product.spuPrice }}</span>
                        </div>
                        <div class="number">
                            1
                        </div>
                        <div class="total">
                            <span>￥{{ product.spuPrice }}</span>
                        </div>
                    </div>

                </div>

                <!-- 结算 -->
                <div class="end_settle">
                    <div class="settle-box">
                        <div class="sb-price">
                            <span>实付款：</span>
                            <span>￥</span>
                            <span>{{ totalAmount }}</span>
                        </div>
                        <div class="to-address">
                            <span>
                                寄送至：
                            </span>
                            <span>
                                {{ changeAddress.province }} {{ changeAddress.city }} {{ changeAddress.region }} {{
                                    changeAddress.detailAddress }}
                            </span>
                        </div>
                        <div class="revice">
                            <span>
                                收货人：
                            </span>
                            <span>
                                {{ changeAddress.name }} {{ changeAddress.phone }}
                            </span>
                        </div>
                    </div>
                </div>
                <div class="order-submit">
                    <div class="pay-order" @click="submitOrder()">
                        提交订单
                    </div>
                </div>
            </div>
        </form>
    </div>
</template>
<script>

import { async } from 'q';
import navcon from '../../components/navcon.vue';
import getUUID from '../../utils/uuid';

export default {
    name: 'buyProduct',
    data() {
        return {
            addressList: [],
            spuIds: [],
            productList: [],
            memberInfoList: [],
            totalAmount: 0,
            memberVo: [],
            changeAddress: '',
            defaultAddress: '',
            orderVo: {
                memberId: '',
                addressId: '',
                spuIds: '',
                price: '',
                orderNote: '对于该订单没有任何描述',
            },
            alipayUrl: window.SITE_CONFIG['baseUrl'] + '/shitou-third-party/alipay/pay',
            payVo: {
                traceNo: '',
                totalAmount: 0.00,
                subject: '',
                alipayTraceNo: '',
                returnUrl: window.SITE_CONFIG["website"]+"/member/accountsetting/orderlist"
            }
        };
    },
    components: {
        navcon,
    },
    methods: {

        /**
         * 提交订单
         */
        submitOrder() {
            this.orderVo.memberId = this.memberVo.id
            this.orderVo.addressId = this.changeAddress.id
            this.orderVo.spuIds = this.spuIds.length <= 0 ? [] : this.spuIds
            this.orderVo.price = this.totalAmount
            this.$http({
                url: this.$http.adornUrl("/shitou-order/shitouorder/order/createOrder"),
                method: 'post',
                data: this.$http.adornData(this.orderVo)
            }).then(({ data }) => {
                if (data.code == 200) {
                    this.payVo.traceNo = data.data.orderSn
                    this.payVo.totalAmount = data.data.payAmount
                    this.payVo.subject = '您购买了: ' + this.spuIds.length + "件数商品"
                    this.payVo.alipayTraceNo = ''
                    this.payVo.returnUrl = window.SITE_CONFIG["website"]+"/member/accountsetting/orderlist"
                    // 支付接口
                    this.$message({
                        type: 'success',
                        message: "订单生成成功"
                    })
                    let form = document.getElementById("alipay")
                    form.action = this.alipayUrl
                    form.traceNo.value = data.data.orderSn
                    form.totalAmount.value = data.data.payAmount
                    form.subject.value = '您购买了: ' + data.data.spuIds + "件数商品" + getUUID()
                    form.alipayTraceNo.value = ''
                    form.returnUrl.value = window.SITE_CONFIG["website"]+"/member/accountsetting/orderlist"
                    form.submit()
                } else {
                    this.$message({
                        type: 'success',
                        message: data.message
                    })
                }
            })
        },


        /**
         * 订单提交成功，进行支付
         */
        aliPay(payVo) {

            this.$http({
                url: this.$http.adornUrl("/shitou-third-party/alipay/pay"),
                method: 'post',
                data: this.$http.adornData(payVo)
            }).then(({ data }) => {
                if (data.code == 200) {
                    this.$message({
                        type: "success",
                        message: "支付成功"
                    })
                } else {
                    this.$message({
                        type: 'warning',
                        message: data.message
                    })
                }
            })
        },


        /**
         * 获取购买的商品
         */
        getAllProduct() {
            this.$http({
                url: this.$http.adornUrl(`/shitou-product/shitouproduct/spuinfo/getProductBySpuIds?spuIds=${this.spuIds}`),
                method: 'post'
            }).then(({ data }) => {
                if (data.code == 200) {
                    this.productList = data.data
                    if (this.productList.length == 0) {
                        this.$router.push({ path: '/' })
                    }
                    this.getMemberInfo()
                } else {
                    this.$message({
                        type: 'warning',
                        message: data.message
                    })
                }
            })
        },

        /**
         * 获取商品发布者的用户信息
         */
        getMemberInfo() {
            let memberIds = []
            this.productList.forEach((product) => {
                memberIds.push(product.memberId)
            })
            this.$http({
                url: this.$http.adornUrl(`/shitou-member/shitoumember/member/getMemberInfoByMemberIds?memberIds=${memberIds}`),
                method: 'post'
            }).then(({ data }) => {
                if (data.code == 200) {
                    this.memberInfoList = data.data
                    this.getTrueProduct()
                    this.getPayAmount()
                } else {
                    this.$message({
                        type: 'warning',
                        message: data.message
                    })
                }
            })
        },

        //组装数据
        getTrueProduct() {
            let len = this.productList.length
            let lenj = this.memberInfoList.length
            for (let i = 0; i < len; i++) {
                for (let j = 0; j < lenj; j++) {
                    if (this.productList[i].memberId === this.memberInfoList[j].memberId) {
                        this.productList[i].nickname = this.memberInfoList[i].nickname
                        this.productList[i].header = this.memberInfoList[i].header
                    }
                }
            }
        },

        /**
         * 获取支付金额
         */
        getPayAmount() {
            this.productList.forEach((product) => {
                this.totalAmount += product.spuPrice
            })
        },

        /**
         * 获取用户收货地址
         */
        getMemberAddress() {
            this.$http({
                url: this.$http.adornUrl("/shitou-member/shitoumember/memberreceiveaddress/memberAddress"),
                method: 'post',
                data: this.$http.adornData({ memberId: this.memberVo.id })
            }).then(({ data }) => {
                if (data.code == 200) {
                    // do
                    this.addressList = data.data;
                    this.addressList.forEach((address) => {
                        if (address.defaultStatus == 1) {
                            this.defaultAddress = address.id;
                            this.changeAddress = address
                        }
                    })
                } else {
                    this.$message({
                        type: 'warning',
                        message: data.message
                    })
                }
            })
        },


        /**
         * 点击选择默认地址
         */
        changeDefaultAddress(address) {
            this.defaultAddress = address.id
            this.changeAddress = address
        },

        /**
         * 前往管理地址
         */
        manageAddress() {
            if (window.location.href.includes("/member/membersetting/takeaddress")) {
                return;
            }
            this.$router.push({ path: "/member/membersetting/takeaddress" })
        },

        /**
         * 判断这些商品是否可购买，不可购买返回首页
         */



    },
    async created() {
        let idS = this.$route.query.spuIds

        // 判断这些商品是否可购买，不可购买返回首页

        let member = await this.$memberInfo()
        if (member != null) {
            this.memberVo = member;
            this.getMemberAddress()
        }
        if (idS.length > 0) {
            let temp = []
            for (let i = 0; i < idS.length; i++) {
                temp.push(idS[i])
            }
            this.spuIds = temp
            this.getAllProduct()
        }



    },
}
</script>
<style scoped>
@import url("../../utils/css/buyproduct.css");
</style>
